package thread;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author zhangxuhui
 * @Date 2023/12/22
 * @email zxh_1633@163.com
 */
public class 异步任务 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        String name = "213";
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<Integer> exceptionally = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("one step init" + Thread.currentThread().getName() + "name:" + name);
            return 1;
        },executorService).thenApply(v -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("two get url" + (v + 1));
            return v + 1;
        }).thenApply(v -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("three check result" + (v + 2));
            return v + 2;
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("four"+v);
                new Thread(() -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                    System.out.println("getr");
                }).start();
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            return null;
        });
        //System.out.println(exceptionally.get());
        //executorService.shutdownNow();
    }
}
